import os
import sys
listonly = False

findexts = ['.mm', '.md', '.pdf', '.txt','.pas']


class findfile:
    def __init__(self):
        super().__init__()
        self.fcount = 0
        self.vcount = 0
        self.result = []

    def visitFile(self, filename, keyword):
        try:
            if not listonly:
                if os.path.splitext(filename)[1].lower() in findexts:
                    if open(filename, 'r', 1, 'UTF-8').read().find(keyword) != -1:
                        # print(filename)
                        self.result.append(filename)
                        self.fcount += 1
                    # print(filename)
                    self.vcount += 1
                else:
                    pass
        except Exception as identifier:
            pass

    def Result(self):
        return list(set(self.result))


def searcher(engine, targetDir, Keyword):
    for root, dirs, files in os.walk(targetDir):
        for name in files:
            engine.visitFile(os.path.join(root, name), Keyword)
        for name in dirs:
            searcher(engine, os.path.join(root, name), Keyword)


def search(*param):
    engine = findfile()
    searcher(engine, param[0], param[1])
    return engine.Result()


if __name__ == "__main__":
    # test('E:/项目/Note/note4program')
    engine = findfile()
    searcher(engine, 'E:/项目/Note/note4program', 'sudo')
    print('Found in %d files, visited %d' % (engine.fcount, engine.vcount))
    print(engine.Result())
